# -*- coding: utf-8 -*-
from bloom_filter import BloomFilter
from jieba import cut_for_search


class Engine(object):
    def __init__(self, bf_size=64):
        # 包含一个 布隆过滤器，一个事件集合，一个倒排词表
        self._bf = BloomFilter(bf_size)
        self._events = []
        self._terms = {}

    def add_event(self, event):
        # 保存事件，并分配事件ID
        eid = len(self._events)
        self._events.append(event)
        # 将分词结果反向映射到事件ID
        for term in cut_for_search(event):
            self._bf.add(term)

            term_set = self._terms.get(term)
            if term_set is None:
                term_set = set()
                self._terms[term] = term_set
            term_set.add(eid)

    def _get_term_set(self, term):
        # 检查布隆过滤器
        if not self._bf.might_has(term):
            return None

        return self._terms.get(term)

    def search(self, some, extra=True):
        res_set = set()
        whole_set = self._get_term_set(some)
        if whole_set:
            res_set.update(whole_set)

        if extra:
            # 对 some 进行分词
            for term in cut_for_search(some):
                term = term.strip()
                if not term:
                    continue
                term_set = self._get_term_set(term)
                if term_set:
                    res_set.update(term_set)

        # 对结果进行排序
        for eid in sorted(res_set):
            yield eid, self._events[eid]
